﻿using System;
using System.ComponentModel;
using GpgApi;

namespace WgpgCore
{
    public sealed class KeyUserInfoNode : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private KeyUserInfo _userInfo;
        private String _fullInfo;

        public KeyNode Key { get; private set; }
        public UInt32 Index { get { return _userInfo.Index; } }
        public Name Name { get { return _userInfo.Name; } }
        public Email Email { get { return _userInfo.Email; } }
        public String Comment { get { return _userInfo.Comment; } }

        public String FullInfo
        {
            get
            {
                if (_fullInfo == null)
                {
                    String r = Name;

                    if (Email != null)
                    {
                        String email = Email.ToString();
                        if (email.Length > 0)
                            r += " <" + email + ">";
                    }

                    if (!String.IsNullOrEmpty(Comment))
                        r += " (" + Comment + ")";

                    _fullInfo = r;
                }

                return _fullInfo;
            }
        }

        internal KeyUserInfoNode(KeyNode key, KeyUserInfo userInfo)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            if (userInfo == null)
                throw new ArgumentNullException("userInfo");

            Key = key;
            _userInfo = userInfo;
            _fullInfo = null;
        }

        private void NotifyPropertyChanged(String name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }

        internal void SetUserInfo(KeyUserInfo userInfo)
        {
            if (userInfo == null)
                throw new ArgumentNullException("userInfo");

            Boolean propertyIndexChanged = !UInt32.Equals(_userInfo.Index, userInfo.Index);
            Boolean propertyNameChanged = !Name.Equals(_userInfo.Name, userInfo.Name);
            Boolean propertyEmailChanged = !Email.Equals(_userInfo.Email, userInfo.Email);
            Boolean propertyCommentChanged = !String.Equals(_userInfo.Comment, userInfo.Comment);

            _userInfo = userInfo;

            if (propertyIndexChanged) NotifyPropertyChanged("Index");
            if (propertyNameChanged) NotifyPropertyChanged("Name");
            if (propertyEmailChanged) NotifyPropertyChanged("Email");
            if (propertyCommentChanged) NotifyPropertyChanged("Comment");

            if (propertyNameChanged || propertyEmailChanged || propertyCommentChanged)
            {
                _fullInfo = null;
                NotifyPropertyChanged("FullInfo");
            }
        }
    }
}
